﻿var gadgetWindow = getGadgetWindow();

var players;

var keeper;
var wingbacks = [];
var defenders = [];
var wingers = [];
var playmakers = [];
var forwards = [];

var Position = 
{
    Unknown : 0,
    Forward : 1,
    Winger : 2,
    Playmaker : 3,
    Wingback : 4,
    Defender : 5,
    Goalkeeper: 6
};

var spinnerControls = [];

function getGadgetWindow() {
    return System.Gadget.document.parentWindow;
}

function resetLineup() {
    keeper = null;
    wingbacks = [];
    defenders = [];
    wingers = [];
    playmakers = [];
    forwards = [];
}

function sortLineupPlayer(index, player) {

    switch (player.AssignedPosition) 
    {
        case Position.Goalkeeper:            
            keeper = player;
            break;
        case Position.Wingback:            
            wingbacks.push(player);
            break;
        case Position.Defender:
            defenders.push(player);
            break;
        case Position.Playmaker:
            playmakers.push(player);
            break;
        case Position.Winger:
            wingers.push(player);
            break;
        case Position.Forward:
            forwards.push(player);
            break;
    }
}

function updateSpinnersForDefaultLineup() {
    spinnerControls["spinCD"].SetCurrentValue(defenders.length);    
    spinnerControls["spinWB"].SetCurrentValue(wingbacks.length);
    spinnerControls["spinIM"].SetCurrentValue(playmakers.length);
    spinnerControls["spinW"].SetCurrentValue(wingers.length);
    spinnerControls["spinF"].SetCurrentValue(forwards.length);

    // Attaching listeners is performed here since each SetCurrentValue invokes a changed value event
    // TOOD: why .each not working here?
    spinnerControls["spinCD"].AttachValueChangedListener(onSpinnerValueChanged);
    spinnerControls["spinWB"].AttachValueChangedListener(onSpinnerValueChanged);
    spinnerControls["spinIM"].AttachValueChangedListener(onSpinnerValueChanged);
    spinnerControls["spinW"].AttachValueChangedListener(onSpinnerValueChanged);
    spinnerControls["spinF"].AttachValueChangedListener(onSpinnerValueChanged);   
}

function updateLineupTable() {
    assignPositionIfAvailable("#gk", keeper);
    
    assignPositionIfAvailable("#wb1", wingbacks[0]);
    assignPositionIfAvailable("#wb2", wingbacks[1]);

    assignTripletPositions("#cd", defenders);

    assignPositionIfAvailable("#w1", wingers[0]);
    assignPositionIfAvailable("#w2", wingers[1]);

    assignTripletPositions("#im", playmakers);

    assignTripletPositions("#f", forwards);

    $("#lineup td").each(function(i) { $(this).fadeIn(50 * (i + 1)); });
}

function assignTripletPositions(divPrefix, collection) {
    switch (collection.length) {
        case 1:
        case 3:
            assignPositionIfAvailable(divPrefix + "2", collection[0]);
            assignPositionIfAvailable(divPrefix + "1", collection[1]);
            assignPositionIfAvailable(divPrefix + "3", collection[2]);
            break;
        case 2:
            assignPositionIfAvailable(divPrefix + "1", collection[0]);
            assignPositionIfAvailable(divPrefix + "3", collection[1]);
            assignPositionIfAvailable(divPrefix + "2", collection[2]);
            break;
    }
}

function assignPositionIfAvailable(td, player) {
    if (player == null)        
    {
        $(td).text("");
        $(td).addClass("hiddenPosition");
        return;
    }

    $(td).removeClass();
    $(td).css("display","none");
    $(td).html("<b>" + player.TargetPlayer.Name + "</b><br/>" +
                "[" + truncate(player.AssignedPositionScore, 2) + "]");
}


function onSpinnerValueChanged(sender, newVal) {
    // TODO: replace spinnerControls indexer with enum    
    var wingbacks =  spinnerControls["spinWB"].GetCurrentValue();
    var defenders = spinnerControls["spinCD"].GetCurrentValue();
    var wingers = spinnerControls["spinW"].GetCurrentValue();
    var playmakers = spinnerControls["spinIM"].GetCurrentValue();
    var forwards = spinnerControls["spinF"].GetCurrentValue();

    resetLineup();
    gadgetWindow.interop.GenerateLineup(players, wingbacks, defenders, wingers, playmakers, forwards);
    $.each(gadgetWindow.interop.Starters, sortLineupPlayer);
    updateLineupTable(); 
}

function getMaxCountForPosition(spinDiv) {
    switch (spinDiv) {
        case "spinWB":
        case "spinW":
            return 2;
        default:
            return 3;
    }
}

function addSpinControl() {
    var spinnerDivs = ["spinCD", "spinWB", "spinF", "spinW", "spinIM"];

    for (i = 0; i < spinnerDivs.length; i++) {
        var spinCtrl = new SpinControl();
        spinCtrl.GetAccelerationCollection().Add(new SpinControlAcceleration(1, 500));
        spinCtrl.GetAccelerationCollection().Add(new SpinControlAcceleration(5, 1750));
        spinCtrl.SetWidth(30);
        spinCtrl.SetMaxValue(getMaxCountForPosition(spinnerDivs[i]));
        spinCtrl.SetMinValue(0);

        $("#" + spinnerDivs[i]).replaceWith(spinCtrl.GetContainer());
        spinCtrl.GetContainer().id = spinnerDivs[i];

        spinCtrl.Tag = spinnerDivs[i];
        spinCtrl.StartListening();

        spinnerControls[spinnerDivs[i]] = spinCtrl;
    }
}

function truncate(number, digits) {
    return Math.floor(number * Math.pow(10, digits)) / Math.pow(10, digits);
}

function showError(msg) {
    $("body").prepend("<span>" + msg + "</span>").css("color", "red");
}

$(document).ready(function() {
    if (!gadgetWindow) {
        showError("Missing something...");
        return;
    }

    //    System.Gadget.Flyout.file = "teamView.html";

    players = gadgetWindow.interop.ToArray(gadgetWindow.MyTeam.Players);

    try {
        //TODO: if not first time, load settings of previous setup, else show default lineup
        addSpinControl();
        gadgetWindow.interop.GenerateDefaultLineup(players);
        $.each(gadgetWindow.interop.Starters, sortLineupPlayer);
        updateLineupTable();
        updateSpinnersForDefaultLineup();
    }
    catch (err) {
        showError(err.description);
    }
});
